<template>
    <view class="pg-center relative z-0">
        <view class="cont mt-25">
            <view class="w-700 fl-ro-cen h-auto fl-ro-cen gap-20 flex-wrap">
                <chargeItem v-for="item in chargeItemList" :chargeItem="item" :isSelected="selectedChargeItem.id === item.id" @handle_click="charge_onclick(item)"></chargeItem>
            </view>
        </view>
    </view>

    <view class="absolute z-1 w-750 p-10-0-10-0 btn">
        <wd-button size="large" type="error" custom-class="w-700 ml-25" @click="charge_it">立即充电</wd-button>
    </view>
</template>

<script setup>
    import { onShow, onLoad } from '@dcloudio/uni-app';
    import { ref } from 'vue';
    import { api_machine_getDtoFull } from '@/api/machine.js';
    import { api_machineOrder_new } from '@/api/machineOrder.js';

    const chargeItemList = ref([]); //充电套餐列表
    const selectedChargeItem = ref({}); //选择的充电套餐

    onLoad(async () => {
        //加载当前机器的详细数据 并获取充电的套餐
        try {
            let res = await api_machine_getDtoFull({ sn: uni.getStorageSync('user').machineSn });
            chargeItemList.value = res.data.machineOption.chargingList;
            console.log(chargeItemList.value);
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none'
            });
        }
    });

    //点击充电套餐
    const charge_onclick = (item) => {
        console.log(item);
        selectedChargeItem.value = item;
    };

    //立即充电
    const charge_it = () => {
        uni.showModal({
            title: '是否选择该套餐',
            success: async (res) => {
                if (res.confirm) {
                    console.log(`选择了${selectedChargeItem.value.name},id是${selectedChargeItem.value.id}`);
                    //访问充电下单接口
                    try {
                        let res = await api_machineOrder_new({
                            machineId: uni.getStorageSync('user').machineId,
                            mocId: selectedChargeItem.value.id
                        });
                        if (res.code === 200) {
                            uni.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                    } catch (error) {
                        uni.showToast({
                            title: error.msg,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            }
        });
    };
</script>

<style lang="scss" scoped>
    .btn {
        bottom: calc(env(safe-area-inset-bottom));
    }
</style>
